<!-- 重力加速度，边界检测 -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>重力加速度，边界检测</title>
</head>

<body>
    <canvas id="canvas"></canvas>
</body>
<script src="../utils.js"></script>
<script>
    // 小球绘制
    class Ball {
        constructor(options) {
            this.x = 0;
            this.y = 0;
            this.r = 200;
            this.fillStyle = 'blue';
            this.strokeStyle = 'black';
            // 小球缩放
            this.scaleX = 1;
            this.scaleY = 1;
            // 小球透明度
            this.alpha = 1;
            Object.assign(this, options);
            return this;
        }
        render(ctx) {
            let { x, y, r, fillStyle, strokeStyle, scaleX, scaleY, alpha } = this;
            // 保存绘图环境
            ctx.save();
            // 开始绘制
            // ctx.beginPath();
            ctx.beginPath();
            ctx.translate(x / 2, y / 2);
            ctx.scale(scaleX, scaleY);
            ctx.strokeStyle = strokeStyle;
            ctx.fillStyle = fillStyle;

            ctx.globalAlpha = alpha;

            ctx.arc(0, 0, r, 0, Math.PI * 2);


            ctx.fill();
            ctx.stroke();
            ctx.restore();
            ctx.closePath();
            return this;
        }
    }
    let canvas = document.getElementById('canvas');
    let ctx = canvas.getContext('2d');
    let w = canvas.width = 1000;
    let h = canvas.height = 1000;
    let ball = new Ball({
        x: w / 2,
        y: h / 2,
        r: 50,
        fillStyle: 'red',
        strokeStyle: 'black',
        scaleX: 1,
        scaleY: 1,
        alpha: 1
    });

    // 定义加速度
    let a = 0.5, v = 0, limit = 0;
    (function move() {
        window.requestAnimationFrame(move);
        ctx.clearRect(0, 0, w, h);
        ball.y += v;
        v += a;

        // 最多跳动20次，然后速度和加速度都为0，停止运动
        if ((ball.y > h - 50) && (limit > 10)) {
            v = 0;
            a = 0;
            ball.y = h - ball.r;
        }


        if (ball.r + ball.y > h) {
            // 到了边界，方向改变，并且存在空气阻力，反弹不到原来高度
            v *= -0.8;
            ball.y = h - ball.r;  // 重置位置
            limit++;
        }

        ball.render(ctx);
    })()

</script>

</html>